//
//  DAULoginVC.m
//  DAU-iOS
//
//  Created by XiangDongMBP on 2016/11/17.
//  Copyright © 2016年 East. All rights reserved.
//

#import "DAULoginVC.h"
#import "DAUTabVC.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "JPUSHService.h"
#import "NSString+XDIsEmpty.h"

@interface DAULoginVC ()

@property (weak, nonatomic) IBOutlet UITextField *serverTextField;
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *pwdTextField;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@end

@implementation DAULoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initSubViews];
    // 取得用户默认信息
    NSUserDefaults *defaults =[ NSUserDefaults standardUserDefaults ];
    
    // 取得 iPhone 支持的所有语言设置
    NSArray *languages =[defaults objectForKey :@"AppleLanguages" ];
    NSLog (@"%@", languages);
    
    // 获得当前iPhone使用的语言
    NSString* currentLanguage =[languages objectAtIndex:0];
    NSLog(@"当前使用的语言：%@",currentLanguage);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initSubViews {
    NSUserDefaults *df = [NSUserDefaults standardUserDefaults];
    self.serverTextField.text = [df objectForKey:DAU_USERDEF_SERVER_DOMAIN];
    self.nameTextField.text = [df objectForKey:DAU_USERDEF_UNAME];
    self.pwdTextField.text = [df objectForKey:DAU_USERDEF_PWD];
    
    self.loginBtn.layer.cornerRadius = 2;
    self.loginBtn.layer.masksToBounds = YES;
    [self.loginBtn addTarget:self action:@selector(loginBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - 按键处理
- (void)loginBtnTapped:(UIButton *)btn {
    // 校验输入参数
    if (!self.serverTextField.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:NSLocalizedString(@"请输入服务器地址", nil)];
        return;
    }
    if (!self.nameTextField.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:NSLocalizedString(@"请输入用户名", nil)];
        return;
    }
    if (!self.pwdTextField.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:NSLocalizedString(@"请输入密码", nil)];
        return;
    }
    
    DAU_APP_DELEGATE.domain = [self.serverTextField.text xd_clearAllWhitespace];
    
    [self requestLogin];
}

- (void)jumpToHomeVC {
    DAUTabVC *tabVC = [[DAUTabVC alloc] init];
    [UIApplication sharedApplication].keyWindow.rootViewController = tabVC;
    //转场动画
    CATransition *anim = [CATransition animation];
    //    anim.type = @"rippleEffect";
    anim.duration = 0.3;
    [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
}

- (void)saveLoginDataToDisk {
    // 极光推送，用用户的uid绑定为别名(注意：家长切换孩子角色那里也要设置)
    NSLog(@"极光推送的别名是%@", self.nameTextField.text);
    [JPUSHService setTags:nil aliasInbackground:self.nameTextField.text];
    
    NSUserDefaults *df = [NSUserDefaults standardUserDefaults];
    [df setObject:[self.serverTextField.text xd_clearAllWhitespace] forKey:DAU_USERDEF_SERVER_DOMAIN];
    [df setObject:self.nameTextField.text forKey:DAU_USERDEF_UNAME];
    [df setObject:self.pwdTextField.text forKey:DAU_USERDEF_PWD];
    [df setBool:YES forKey:DAU_USERDEF_AUTOLOGIN];
}

#pragma mark - 网络请求
- (void)requestLogin {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSString *urlStr = [DAUUrlProtocolMerger apiLogin];
    NSDictionary *pars = @{@"account"  : self.nameTextField.text,
                           @"password" : self.pwdTextField.text,
                           @"blueteeth_uuid" : @"abcd"};
    [XDAFHttpRequest GET:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"登录成功返回%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[@"errCode"] integerValue] == 200) {
            [self saveLoginDataToDisk];
            [self jumpToHomeVC];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[@"msg"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"登录失败%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:NSLocalizedString(@"网络请求失败", nil)];
    }];
}

@end
